package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Async("taskExecutor")
    @Override
    public void hotCommentExecutor(ApComment apComment) {
    log.info("异步计算评论方法  执行start==================>   {}",apComment);
        Query query = Query.query(Criteria.where("articleId").is(apComment.getArticleId()).and("flag").is(1)).with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        if(CollectionUtils.isEmpty(apComments)||apComments.size()<5){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComments);
            return;
        }
        ApComment lastComment = apComments.get(apComments.size() - 1);
        if(apComment.getLikes()>lastComment.getLikes()){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComments);
            lastComment.setFlag((short) 0);
            mongoTemplate.save(lastComment);
        }

        log.info("异步计算评论方法  执行end==================> ");

    }
}
